using System.Collections;
using System.Collections.Generic;
using Dou.Scripts.Battle;
using Dou.Scripts.Core.Helpers;
using UnityEngine;

namespace abilities.triggers
{
    public class AbilityTriggerDistanceTo : AbilityTrigger
    {
        TargetObject target;

        public override void Start()
        {
            Debug.Log("AbilityTriggerTimer.start %p" + this);

            UnitObject owner = context.AbilityManager.Owner as UnitObject;
            List<UnitObject> units = UnitObject.UnitsInSight();
            foreach (var it in units)
            {
                if (it.articleId == prototype.articleId && owner != it && !it.isDead())
                {
                    target = new TargetObject(it);
                    break;
                }
            }

            if (target != null && iUp == null)
                iUp = BattleSimulator.Instance.StartCoroutine(IUpdate());
        }

        public override void Stop()
        {
            Debug.Log("AbilityTriggerTimer.stop %p" + this);
            target = null;
            CoroutineHelper.StartTimer();
            if(iUp != null)
                BattleSimulator.Instance.StopCoroutine(iUp);
            iUp = null;
        }

        private Coroutine iUp;
        IEnumerator IUpdate()
        {
            yield return 1;
            while (iUp != null)
            {
                Update(Time.deltaTime);
            }
        }
        

        public override void Update(float time)
        {
            float distance = Vector2.Distance(target.unit.position, context.AbilityManager.Owner.position);
            if ((prototype.minRadius < 0 || distance >= prototype.minRadius) && (prototype.maxRadius < 0 || distance <= prototype.maxRadius))
            {
                OnPerform();
            }
        }
    }
}